<template>
  <div class="test-center-area">
    <div class="test-page">
      <div class="test-header">
        <img src="/head.png" alt="head" />
      </div>
      <div class="test-main no-footer">
        <div class="test-questions">
          <Radio
            :questions="questions"
            v-model="answers"
            @submit="handleSubmit"
          />
        </div>
        <div class="test-aside wide-aside">
          <CountdownCard
            :remainingTime="remainingTime"
            :progressPercent="progressPercent"
            :answeredCount="answeredCount"
            :totalQuestions="totalQuestions"
          />
          <div class="cheat-count">切屏/违规次数：{{ count }}</div>
          <AnswerSheet
            :questions="questions"
            :answers="answers"
            @submit="handleSubmit"
          />
        </div>
      </div>
      <WarningDialog
        v-model="showWarning"
        :data="warningData"
        title="警告"
        @close="handleClose"
      />
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted, onBeforeUnmount, computed } from "vue";
import { useRouter, useRoute } from "vue-router";
import { useAntiCheat } from "../../layout/antiCheat";
import { useStore } from "vuex";
import WarningDialog from "../../components/warningDialog.vue";
// import surveyData from "./components/surveyData.js";
import Radio from "./components/radio.vue";
import { reactive } from "vue";
import AnswerSheet from "./components/answerSheet.vue";
import CountdownCard from "./components/CountdownCard.vue";
import { getSurveyList, getEmployeeList, submitAnswer } from "../../api/api";
import surveyData from "./components/surveyData.js";
import { ElMessage } from "element-plus";

const router = useRouter();
const route = useRoute();
const store = useStore();
const count = ref(0);
const showWarning = ref(false);
const warningData = ref({ message: "" });
const answers = reactive({}); // 用于收集每题答案
const questions = ref([]);
const surveyId = ref(null);
const employeeId = computed(() => store.state.employeeId);

// 倒计时逻辑
const totalSeconds = 60 * 60; // 60分钟
const remainingTime = ref(totalSeconds);
let timer = null;

function startTimer() {
  timer = setInterval(() => {
    if (remainingTime.value > 0) {
      remainingTime.value--;
    } else {
      clearInterval(timer);
      handleSubmit();
    }
  }, 1000);
}

onMounted(async () => {
  store.commit("setEnteredTest", true);
  antiCheat.start();
  startTimer();

  // 调用后端接口获取问卷列表和员工列表
  try {
    const [surveyRes] = await Promise.all([getSurveyList()]);

    // 获取第一个问卷的surveyId并请求题目列表
    const surveyList = surveyRes.data.data || [];
    if (surveyList.length > 0) {
      surveyId.value = surveyList[0].surveyId;
      const { getSurveyQuestions } = await import("../../api/api");
      const questionRes = await getSurveyQuestions(surveyId.value);

      questions.value = questionRes.data.data || [];
    }
  } catch (err) {
    console.error("接口请求失败", err);
    // 使用本地 surveyData 假数据作为备用
  }
});

onBeforeUnmount(() => {
  antiCheat.stop();
  if (timer) clearInterval(timer);
});

function handleChat(msg) {
  warningData.value.message = msg;
  showWarning.value = true;
  count.value++;
  if (count.value >= 3 && !submitting.value) {
    ElMessage.warning("违规次数达到 3 次，系统已自动提交试卷！");
    handleSubmit();
  }
}

function handleClose() {
  showWarning.value = false;
  antiCheat.requestFullscreen();
}

const antiCheat = useAntiCheat({
  // chat回调
  onChat: handleChat,
});

function goResult() {
  antiCheat.stop();
  if (timer) clearInterval(timer);
  router.push("/start/result");
}

const submitting = ref(false);
// 修改 handleSubmit 标记，避免重复多次提交
function handleSubmit() {
  if (submitting.value) return;
  submitting.value = true;
  // 拼接提交参数
  const answerArr = questions.value.map((q) => ({
    questionId: q.questionId,
    score: answers[q.questionId],
  }));
  const params = {
    surveyId: surveyId.value,
    employeeId: employeeId.value,
    answers: answerArr,
  };
  console.log("提交参数:", params);
  submitAnswer(params)
    .then((res) => {
      console.log("提交结果:", res.data);
      goResult();
    })
    .catch((err) => {
      console.error("提交失败", err);
    });
}

// 答题进度
const totalQuestions = computed(() => questions.value.length);
const answeredCount = computed(
  () =>
    Object.keys(answers).filter(
      (k) =>
        answers[k] !== undefined && answers[k] !== null && answers[k] !== ""
    ).length
);
const progressPercent = computed(() =>
  totalQuestions.value === 0
    ? 0
    : Math.round((answeredCount.value / totalQuestions.value) * 100)
);
</script>

<style scoped>
.test-center-area {
  min-height: 100vh;
  background: #fafbfc;
}
.test-page {
  display: flex;
  flex-direction: column;
  background-color: #f6f6f6;
  min-height: 100vh;
}
.test-header {
  width: 100%;
  height: 200px;
  /* background: url("./head.png") no-repeat center center; */
  border-radius: 10px;
  border: none;
}
.test-main.no-footer {
  display: flex;
  flex: 1 1 0;
  min-height: 0;
  padding: 0 24px;
  box-sizing: border-box;
  min-width: 75vw;
  margin: 0 auto;
  justify-content: center;
}
.test-questions {
  flex: 6.5; /* 扩大题目区域宽度 */
  display: flex;
  flex-direction: column;
  align-items: center;
  overflow-y: auto;
  overflow-x: hidden;
  padding-right: 16px;
  min-width: 0;
  word-break: break-all;
  white-space: normal;
  justify-content: flex-start;
}
.test-aside {
  flex: 3.5; /* 缩小侧栏默认占比 */
  border-left: 1px solid #eee;
  padding-left: 24px;
  min-width: 0;
  display: flex;
  flex-direction: column;
  align-items: flex-start;
  margin-top: -20px; /* 整体上挪20px */
}
.test-aside.wide-aside {
  flex: 3.5; /* 与默认保持一致，方便后续如需再调 */
  /* justify-content: center; */
  align-items: center;
  padding-left: 24px;
  margin-top: -20px; /* 整体上挪20px */
}
.test-progress-card {
  width: 100%;
  background: #fff;
  border-radius: 10px;
  border: none;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.04);
  margin-bottom: 18px;
  padding: 32px 32px 28px 32px;
  box-sizing: border-box;
  display: flex;
  flex-direction: column;
  align-items: center;
}
.progress-header {
  display: flex;
  align-items: center;
  font-size: 20px;
  color: #222;
  margin-bottom: 12px;
  font-weight: bold;
}
.progress-icon {
  font-size: 22px;
  margin-right: 8px;
  color: #bbb;
  font-weight: normal;
}
.progress-title {
  font-size: 20px;
  color: #222;
  font-weight: bold;
}
.progress-timer {
  font-size: 38px;
  color: #ff6700;
  font-weight: bold;
  margin-bottom: 22px;
  margin-top: 2px;
  letter-spacing: 2px;
  text-align: center;
}
.progress-bar-wrap {
  width: 100%;
  margin-top: 8px;
}
.progress-bar-bg {
  width: 100%;
  height: 18px;
  background: #ededed;
  border-radius: 12px;
  position: relative;
  overflow: hidden;
}
.progress-bar-fg {
  height: 100%;
  background: #2196f3;
  border-radius: 12px 0 0 12px;
  transition: width 0.3s;
}
.progress-bar-labels {
  display: flex;
  justify-content: space-between;
  margin-top: 6px;
  font-size: 15px;
  align-items: flex-end;
}
.progress-bar-left {
  color: #2196f3;
  font-weight: 500;
}
.progress-bar-right {
  color: #bbb;
  font-weight: 400;
}
.cheat-count {
  font-size: 16px;
  color: #f56c6c;
  margin-bottom: 16px;
  font-weight: bold;
}
.test-root {
  min-height: 100vh;
  background: #fafbfc;
  min-width: 320px;
  width: 100vw;
}
</style>
